package org.sibutu.plugin.struts2.jcr.wrapper;


import org.sibutu.plugin.struts2.jcr.wrapper.NodeWrapperImpl;
import org.sibutu.plugin.struts2.jcr.wrapper.WrapperFactory;
import org.sibutu.plugin.struts2.jcr.wrapper.PropertyNullWrapperImpl;
import org.sibutu.kernel.persistence.jcr.utils.JcrSecurityHelper;
import org.sibutu.kernel.Hierarchical;

import javax.jcr.*;

/**
 *  Jcr node Wrapper with to purposes
 * 1. Emulates tree structure for proper permittions handling
 * 2. Returns empty properties if no property found (default jcr behavior is to throw exception)
 * @author : Max Skripnikov
 */
public class SibutuNodeWrapperImpl extends NodeWrapperImpl {
  private JcrSecurityHelper jcrSecurityHelper;

  public SibutuNodeWrapperImpl(Node node, WrapperFactory wrapperFactory, JcrSecurityHelper jcrSecurityHelper) {
    super(node,wrapperFactory);
    this.jcrSecurityHelper = jcrSecurityHelper;
  }

  public Hierarchical getSecurityObject(){
    return jcrSecurityHelper.getSecurityObject(this);
  }

  public Property getProperty(String name) throws PathNotFoundException, RepositoryException {
    Property property = super.getProperty(name);
    if(property==null){
      return new PropertyNullWrapperImpl(this,name,wrapperFactory);
    }
    return wrapperFactory.createWrapped(property);
  }

  public Node getParent() throws AccessDeniedException, RepositoryException {
    Node parent = super.getParent();
    if(parent==null || parent.getName().equals("jcr:root")){
      Node parentNode = JcrSecurityHelper.getInstance().getParentNode(this);
      if(parentNode!=null){
        return wrapperFactory.createWrapped(parentNode);
      }
    }
    return wrapperFactory.createWrapped(parent);
  }

}